// 1688商品搜索系统前端逻辑

class ProductSearchApp {
    constructor() {
        this.apiBase = '/api';
        this.currentPage = 1;
        this.itemsPerPage = 20;
        this.products = [];
        this.analysis = {};
        this.charts = {};
        
        this.init();
    }
    
    init() {
        this.bindEvents();
    }
    
    bindEvents() {
        // 搜索表单提交
        document.getElementById('searchForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.searchProducts();
        });
        
        // 导出按钮
        document.getElementById('exportBtn').addEventListener('click', () => {
            this.exportCSV();
        });
    }
    
    async searchProducts() {
        const keyword = document.getElementById('keyword').value.trim();
        const province = document.getElementById('province').value;
        const city = document.getElementById('city').value.trim();
        
        if (!keyword) {
            alert('请输入搜索关键字');
            return;
        }
        
        // 显示加载状态
        this.showLoading(true);
        this.hideResults();
        
        try {
            const response = await fetch(`${this.apiBase}/search`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    keyword: keyword,
                    province: province,
                    city: city,
                    max_products: 100
                })
            });
            
            if (!response.ok) {
                throw new Error(`搜索失败: ${response.status}`);
            }
            
            const data = await response.json();
            this.products = data.products;
            this.analysis = data.analysis;
            
            // 显示结果
            this.showResults();
            this.updateStats();
            this.renderProducts();
            this.renderCharts();
            
            // 启用导出按钮
            document.getElementById('exportBtn').disabled = false;
            
        } catch (error) {
            console.error('搜索错误:', error);
            alert(`搜索失败: ${error.message}`);
        } finally {
            this.showLoading(false);
        }
    }
    
    showLoading(show) {
        document.getElementById('loading').style.display = show ? 'block' : 'none';
    }
    
    hideResults() {
        document.getElementById('resultsContainer').style.display = 'none';
    }
    
    showResults() {
        document.getElementById('resultsContainer').style.display = 'block';
    }
    
    updateStats() {
        const { analysis } = this;
        
        document.getElementById('totalProducts').textContent = analysis.total_products || 0;
        document.getElementById('avgPrice').textContent = `¥${(analysis.price_analysis?.avg || 0).toFixed(2)}`;
        document.getElementById('avgSales').textContent = Math.round(analysis.sales_analysis?.avg || 0);
        
        // 计算总体完整率
        const completeness = analysis.completeness || {};
        const total = analysis.total_products || 1;
        const avgCompleteness = Object.values(completeness).reduce((sum, val) => sum + val, 0) / (Object.keys(completeness).length * total) * 100;
        document.getElementById('completeness').textContent = `${avgCompleteness.toFixed(1)}%`;
    }
    
    renderProducts() {
        const container = document.getElementById('productsList');
        const startIndex = (this.currentPage - 1) * this.itemsPerPage;
        const endIndex = startIndex + this.itemsPerPage;
        const pageProducts = this.products.slice(startIndex, endIndex);
        
        container.innerHTML = pageProducts.map(product => `
            <div class="product-card card mb-3">
                <div class="row g-0">
                    <div class="col-md-2">
                        <img src="${product.image || '/api/placeholder/150/150'}" 
                             class="img-fluid rounded-start" 
                             alt="商品图片"
                             style="height: 150px; object-fit: cover;">
                    </div>
                    <div class="col-md-10">
                        <div class="card-body">
                            <h6 class="card-title">
                                <a href="${product.link}" target="_blank" class="text-decoration-none">
                                    ${product.title}
                                </a>
                            </h6>
                            <div class="row">
                                <div class="col-md-3">
                                    <strong class="text-danger">价格: ${product.price}</strong>
                                </div>
                                <div class="col-md-3">
                                    <span class="text-muted">销量: ${product.sales}</span>
                                </div>
                                <div class="col-md-3">
                                    <span class="text-info">供应商: ${product.supplier || 'N/A'}</span>
                                </div>
                                <div class="col-md-3">
                                    <span class="text-success">回头率: ${product.return_rate || 'N/A'}</span>
                                </div>
                            </div>
                            <div class="row mt-2">
                                <div class="col-md-6">
                                    <span class="text-primary">公司: ${product.company_name || 'N/A'}</span>
                                </div>
                                <div class="col-md-6">
                                    <div class="tags">
                                        ${product.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `).join('');
        
        this.renderPagination();
    }
    
    renderPagination() {
        const totalPages = Math.ceil(this.products.length / this.itemsPerPage);
        const pagination = document.getElementById('pagination');
        
        let paginationHTML = '';
        
        // 上一页
        paginationHTML += `
            <li class="page-item ${this.currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="app.goToPage(${this.currentPage - 1})">
                    <i class="fas fa-chevron-left"></i>
                </a>
            </li>
        `;
        
        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === 1 || i === totalPages || (i >= this.currentPage - 2 && i <= this.currentPage + 2)) {
                paginationHTML += `
                    <li class="page-item ${i === this.currentPage ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="app.goToPage(${i})">${i}</a>
                    </li>
                `;
            } else if (i === this.currentPage - 3 || i === this.currentPage + 3) {
                paginationHTML += '<li class="page-item disabled"><span class="page-link">...</span></li>';
            }
        }
        
        // 下一页
        paginationHTML += `
            <li class="page-item ${this.currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="app.goToPage(${this.currentPage + 1})">
                    <i class="fas fa-chevron-right"></i>
                </a>
            </li>
        `;
        
        pagination.innerHTML = paginationHTML;
    }
    
    goToPage(page) {
        const totalPages = Math.ceil(this.products.length / this.itemsPerPage);
        if (page >= 1 && page <= totalPages) {
            this.currentPage = page;
            this.renderProducts();
            
            // 滚动到顶部
            document.getElementById('resultsContainer').scrollIntoView({ behavior: 'smooth' });
        }
    }
    
    renderCharts() {
        this.renderCompletenessChart();
        this.renderPriceChart();
        this.renderTagsChart();
        this.renderSampleProducts();
    }
    
    renderCompletenessChart() {
        const ctx = document.getElementById('completenessChart').getContext('2d');
        const completeness = this.analysis.completeness || {};
        
        if (this.charts.completeness) {
            this.charts.completeness.destroy();
        }
        
        this.charts.completeness = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['标题', '价格', '销量', '链接', '标签', '图片'],
                datasets: [{
                    data: [
                        completeness.title || 0,
                        completeness.price || 0,
                        completeness.sales || 0,
                        completeness.link || 0,
                        completeness.tags || 0,
                        completeness.image || 0
                    ],
                    backgroundColor: [
                        '#FF6384',
                        '#36A2EB',
                        '#FFCE56',
                        '#4BC0C0',
                        '#9966FF',
                        '#FF9F40'
                    ]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }
    
    renderPriceChart() {
        const ctx = document.getElementById('priceChart').getContext('2d');
        const priceAnalysis = this.analysis.price_analysis || {};
        
        if (this.charts.price) {
            this.charts.price.destroy();
        }
        
        this.charts.price = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['最低价', '平均价', '最高价'],
                datasets: [{
                    label: '价格 (元)',
                    data: [
                        priceAnalysis.min || 0,
                        priceAnalysis.avg || 0,
                        priceAnalysis.max || 0
                    ],
                    backgroundColor: ['#36A2EB', '#FFCE56', '#FF6384']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
    
    renderTagsChart() {
        const ctx = document.getElementById('tagsChart').getContext('2d');
        const topTags = this.analysis.top_tags || [];
        
        if (this.charts.tags) {
            this.charts.tags.destroy();
        }
        
        const top10Tags = topTags.slice(0, 10);
        
        this.charts.tags = new Chart(ctx, {
            type: 'horizontalBar',
            data: {
                labels: top10Tags.map(tag => tag[0]),
                datasets: [{
                    label: '出现次数',
                    data: top10Tags.map(tag => tag[1]),
                    backgroundColor: '#4BC0C0'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
    
    renderSampleProducts() {
        const container = document.getElementById('sampleProducts');
        const sampleProducts = this.products.slice(0, 3);
        
        container.innerHTML = sampleProducts.map(product => `
            <div class="mb-3 p-3 border rounded">
                <h6 class="text-truncate">${product.title}</h6>
                <div class="row">
                    <div class="col-6">
                        <small class="text-muted">价格: <strong class="text-danger">${product.price}</strong></small>
                    </div>
                    <div class="col-6">
                        <small class="text-muted">销量: ${product.sales}</small>
                    </div>
                </div>
                <div class="mt-2">
                    ${product.tags.slice(0, 3).map(tag => `<span class="tag">${tag}</span>`).join('')}
                </div>
            </div>
        `).join('');
    }
    
    async exportCSV() {
        try {
            const response = await fetch(`${this.apiBase}/api/export/csv`);
            
            if (!response.ok) {
                throw new Error('导出失败');
            }
            
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'products.csv';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            
        } catch (error) {
            console.error('导出错误:', error);
            alert(`导出失败: ${error.message}`);
        }
    }
}

// 初始化应用
const app = new ProductSearchApp();

// Chart.js 兼容性处理
if (typeof Chart !== 'undefined') {
    // 处理 Chart.js v3+ 的 horizontalBar 类型
    Chart.register({
        id: 'horizontalBar',
        beforeInit: function(chart) {
            if (chart.config.type === 'horizontalBar') {
                chart.config.type = 'bar';
                chart.config.options = chart.config.options || {};
                chart.config.options.indexAxis = 'y';
            }
        }
    });
}